﻿using UnityEngine;
using System.Collections;

public class SceneManager : MonoBehaviour {

	public Creater backgroundCreater;
	public Creater border;
	public Creater mapCreater;
	public Creater player;

	private bool isLoading;

	private string tips;

	// Use this for initialization
	void Start () {
		tips = "Loading";
		isLoading = true;
		GameSetting.GAME_START = false;
		StartCoroutine(InitScene(new Vector2(Screen.width/100,Screen.height/100)));
	}

	void OnGUI(){
		if(isLoading){
			GUI.backgroundColor = new Color(0,0,1,1);
			GUI.Box(new Rect(0,0,Screen.width,Screen.height),"Load");
			GUI.TextField(new Rect(Screen.width/2 - 100,Screen.height/2 - 50,200,20),tips);
		}
	}

	IEnumerator InitScene(Vector2 size){
		//初始化mapCreater
		tips = "Laod " + mapCreater.createrPath;
		ResourceRequest resourceRequestM = Resources.LoadAsync<GameObject> (mapCreater.createrPath);
		while (!resourceRequestM.isDone) {
          yield return 0;
        }
		GameObject mapCreaterObj = Instantiate(resourceRequestM.asset as GameObject);
        TileMaperCreater mapperCreater = mapCreaterObj.GetComponent<TileMaperCreater>();
        mapperCreater.CreaterMap(size);
		Vector2 mapCenterPosition = mapperCreater.MapCenterPosition();
        //初始化BackgroundCreater
        tips = "Laod " + backgroundCreater.tipsName;
		ResourceRequest resourceRequestBC = Resources.LoadAsync<GameObject>(backgroundCreater.createrPath);
        while (!resourceRequestBC.isDone)
        {
            yield return 0;
        }
        GameObject backgroundCreaterObj = Instantiate(resourceRequestBC.asset as GameObject);
		backgroundCreaterObj.SendMessage("InintBackground",mapCenterPosition);
        //初始化Player
		tips = "Laod " + player.createrPath;
		GameObject playerObj = Instantiate(Resources.Load<GameObject>(player.createrPath));
       	playerObj.transform.position = new Vector3(mapCenterPosition.x, mapCenterPosition.y, playerObj.transform.position.z);
		playerObj.SendMessage("InitPlayer");
		//初始化空气墙
		ResourceRequest resourceRequestB = Resources.LoadAsync<GameObject>(border.createrPath);
        while (!resourceRequestBC.isDone)
        {
            yield return 0;
        }
		GameObject borderObj = Instantiate(resourceRequestB.asset as GameObject);
		borderObj.SendMessage("InitBorder",size);
		borderObj.transform.position = (mapCenterPosition);
		//初始化摄像机位置
		Camera.main.GetComponent<CameraAuto>().SetCenterPosition(mapCenterPosition);
		//初始化刷怪点
		//初始化魔王位置

		//初始化结束
		GameSetting.GAME_START = true;
		isLoading = false;
		Resources.UnloadUnusedAssets();
	}

	[System.Serializable]
	public class Creater{
		public string createrPath;
		public string tipsName;
	}
}
